
package com.oauth.eurekaoauthserver.service;


import com.oauth.eurekaoauthserver.common.PasswordEncoderEnum;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @Auther: IceZhang
 * @Date: 2018/8/3 13:07
 * @Description:
 */
@Component
public class PasswordEncoderImpl implements PasswordEncoder {

    /**
     * @see org.springframework.security.crypto.password.PasswordEncoder#encode(CharSequence)
     **/
    @Override
    public String encode(CharSequence rawPassword) {
        return null;
    }

    /**
     * @see org.springframework.security.crypto.password.PasswordEncoder#matches(CharSequence, String)
     **/
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        String password = rawPassword.toString();
      if (password == null || encodedPassword == null) return false;
      String[] encodedPasswords = encodedPassword.split(":");// 标示加密方式
      int length = encodedPasswords.length;
      String encodedType = encodedPasswords[0];
      if (PasswordEncoderEnum.equals.name().equals(encodedType)) {
          if (length == 2) {
              String passwordDb = encodedPasswords[1];
              if (password.equals(passwordDb)) {
                  return true;
              }
          }
      } else if (PasswordEncoderEnum.md5Hash.name().equals(encodedType)) {
          if (length == 4) {
              String username = encodedPasswords[1];
              String passwordDb = encodedPasswords[2];
              String salt = encodedPasswords[3];
              if (passwordDb.equals(new Md5Hash(password, username + salt, 2).toBase64())) {
                  return true;
              }
          }
      }
      return false;
    }

}
